local util = require "util"
local conf = require "conf"
local require = require
local setmetatable = setmetatable
local error = error
local table = table
local ngx = ngx
local os = os
local string = string
local tonumber = tonumber
package.cpath = "/usr/nginx/?.so;;"
local json = require 'cjson'
module(...)
_VERSION = '0.1'


function info(user, args)
    local db = conf.get_mysql()
    local res  = {}
    local sql = "SELECT id,lng,lat,alt,name FROM `spoint` WHERE `spoint`.disabled = 0"
    sql = sql .. " AND `spoint`.aid in (" ..  table.concat(user.aids, ",") .. ")"
    sql = sql .. " AND `spoint`.org_id in (" ..  table.concat(user.orgIds, ",") .. ")"

    local sql2 = "SELECT count(id) FROM `plane` WHERE 1=1"
    sql2 = sql2 .. " AND `plane`.aid in  (" ..  table.concat(user.aids, ",") .. ")"
    sql2 = sql2 .. " AND `plane`.org_id in  (" ..  table.concat(user.orgIds, ",") .. ")"

    local sql3 = "SELECT `order`.fid, (SELECT detail FROM `route` WHERE `route`.id = `order`.route) AS routeDetail, (SELECT name from spoint where id = (SELECT sid from route where id = `order`.route)) AS sname, (SELECT name from spoint where id = (SELECT eid from route where id = `order`.route)) AS ename FROM `order` inner join `plane` on `plane`.id = `order`.fid WHERE 1=1"
    sql3 = sql3 .. " AND `plane`.aid in  (" ..  table.concat(user.aids, ",") .. ") AND `plane`.status = 1 AND `order`.state = 2"
    sql3 = sql3 .. " AND `plane`.org_id in  (" ..  table.concat(user.orgIds, ",") .. ")"
    local area = "SELECT name from area where id = " .. user.aid

    local spointCount = db:query(sql)
    local totalPlane = db:query(sql2)
    local details = db:query(sql3)
    local area = db:query(area)
    res["spointCount"] = spointCount
    res[ "totalPlane"] = totalPlane[1]["count(id)"]
    res["details"] = details
    res["area"] = area[1]["name"]
    -- ngx.log(ngx.ERR, sql3)
    -- ngx.log(ngx.ERR, json.encode(res))
    if not res then
        ngx.print(json.encode({
            err = 1,
            msg = '未找到相应的信息'
        }))
        ngx.exit(200)
    else
        ngx.print(json.encode({
            err = 0,
            msg = res
        }))
        ngx.exit(200)
    end
end

function default(args)
    local user = conf.parse_token(args)
    -- conf.check_permissions(uid, "spoint")
    if args.action == 'create' then

    elseif args.action == 'info' then
        info(user, args)
    end
end

local class_mt = {
    __newindex = function (table, key, val)
        error('attempt to write to undeclared variable "' .. key .. '"')
    end
}
setmetatable(_M, class_mt)
